package cc.mcyx.ychat.websocket.listener

import cc.mcyx.ychat.service.impl.AuthService
import cc.mcyx.ychat.websocket.RootWebSocket
import cc.mcyx.ychat.websocket.event.SubscribeWsEvent
import cc.mcyx.ychat.websocket.event.WsData
import com.corundumstudio.socketio.SocketIOClient
import com.corundumstudio.socketio.annotation.OnConnect
import com.corundumstudio.socketio.annotation.OnDisconnect
import com.corundumstudio.socketio.annotation.OnEvent
import org.springframework.beans.factory.annotation.Autowired

@SubscribeWsEvent
class WsAcceptListener {

    @Autowired
    lateinit var rootWebSocket: RootWebSocket

    @Autowired
    lateinit var authService: AuthService


    @OnConnect
    fun connection(ioc: SocketIOClient) {
        if (ioc.isChannelOpen) println("client connected: ${ioc.sessionId}")
    }

    @OnEvent("ck")
    fun onMessage(wsData: WsData) {
        val uuid = wsData.socketIOClient.sessionId
        // ws 身份验证且绑定
        try {
            val token = wsData.data as String
            println(token)
            authService.checkTokenEx(token)
            val uid = authService.tokenToUid(token)
            rootWebSocket.accept(uuid, uid)
            println(rootWebSocket.getUidSession(uid))
        } catch (throwable: Throwable) {
            rootWebSocket.closeAccept(uuid)
            wsData.socketIOClient.disconnect()
        }
    }

    @OnDisconnect
    fun onDisconnect(disconnect: SocketIOClient) {

    }
}